<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

Class AlgorithmAction extends NewzanAction
{
	public function condition()
	{
		$user_id = $this->me['user_id'];
		// 获取账户所有推广组
		$dlist = M('semiautotag')->where("user_id = {$user_id} AND platform = 0")->order('add_time desc')->select();
		$siluList = array(
				'custom' => array(
						'total_items' => 0,
						'items' => array()
					),
				'public' => array(
						'total_items' => 0,
						'items' => array()
					),
				'platform' => array(
						'total_items' => 0,
						'items' => array()
					)
			);
		if($dlist) {
			$adgroupMdl = new AdgroupModel;
			foreach ($dlist as $key => &$list) {
				$list['content'] = analyticalThinking($list['content']);
				$list['content'] .= "<div style=\"margin-top:10px;\">数据来源：" . (($list['data_source'] == 1) ? '计算机' : '无线') . "</div>";
				$list['add_time'] = date('Y-m-d H:i', $list['add_time']);
				if((int)$list['type'] == 3) {
					$siluList['custom']['total_items']++;
					$siluList['custom']['items'][] = $list;
				} else {
					$siluList['public']['total_items']++;
					$siluList['public']['items'][] = $list;
				}
			}
			unset($dlist);
		}
		$dlist = M('semiautotag_platform')->field('id,menu_path,add_time,update_time')->where("user_id = {$user_id}")->select();
		if($dlist) {
			foreach ($dlist as $key => &$list) {
				$list['last_time'] = $list['update_time'] ? date('Y-m-d H:i', $list['update_time']) : date('Y-m-d H:i', $list['add_time']);
				unset($list['update_time']);
				unset($list['add_time']);
				$tmpName = array();
				$tmp = $list['menu_path'];
				while (strlen($tmp) > 0) {
					$i = M('semiautotag_menu')->where("menu_path = '{$tmp}'")->getField('menu_name');
					$tmpName[] = strlen($tmp) != 2 ? "<a href=\"/algorithm/platform?pid={$tmp}\">{$i}</a>" : "<a href=\"javascript:;\">{$i}</a>";
					$tmp = substr($tmp, 0, strlen($tmp)-2);

				}
				$list['menu_full_name'] = implode(' - ', array_reverse($tmpName));
			}
			$siluList['platform']['total_items'] = count($dlist);
			$siluList['platform']['items'] = $dlist;
			unset($dlist);
		}
		$this->assign('list', $siluList);
		$this->assign('user_id', $user_id);
		$this->loadJS('custom.siluhelper');
		$this->display();
	}

	public function semiauto_list()
	{
		$user_id = $this->me['user_id'];
		// 获取账户所有推广组
		$dlist = M('semiautotag')->where("user_id = {$user_id} AND platform = 0")->order('add_time desc')->select();
		$siluList = array(
			'custom' => array(
				'total_items' => 0,
				'items' => array()
			),
			'public' => array(
				'total_items' => 0,
				'items' => array()
			),
			'platform' => array(
				'total_items' => 0,
				'items' => array()
			)
		);
		if($dlist) {
			$adgroupMdl = new AdgroupModel;
			foreach ($dlist as $key => &$list) {
				$list['content'] = analyticalThinking($list['content']);
				$list['content'] .= "<div style=\"margin-top:10px;\">数据来源：" . (($list['data_source'] == 1) ? '计算机' : '无线') . "</div>";
				$list['add_time'] = date('Y-m-d H:i', $list['add_time']);
				if((int)$list['type'] == 3) {
					if($list['adgroup_id']){
						$existing_adgroup_ids = array();
						$adgroup_ids = explode(',',$list['adgroup_id']);
						foreach($adgroup_ids as $adgroup_id){
							if(M('adgroups')->where("adgroup_id={$adgroup_id}")->find()){
								$existing_adgroup_ids[] = $adgroup_id;
							}
						}
						$list['adgroup_id'] = join(',', $existing_adgroup_ids);
					}
					if($list['campaign_id']){
						$existing_campaign_ids = array();
						$campaign_ids = explode(',',$list['campaign_id']);
						foreach($campaign_ids as $campaign_id){
							if(M('campaigns')->where("campaign_id={$campaign_id}")->find()){
								$existing_campaign_ids[] = $campaign_id;
							}
						}
						$list['campaign_id'] = join(',', $existing_campaign_ids);
					}
					$siluList['custom']['total_items']++;
					$siluList['custom']['items'][] = $list;
				} else {
					$siluList['public']['total_items']++;
					$siluList['public']['items'][] = $list;
				}
			}
			unset($dlist);
		}
		$dlist = M('semiautotag_platform')->field('id,menu_path,add_time,update_time')->where("user_id = {$user_id}")->select();
		if($dlist) {
			foreach ($dlist as $key => &$list) {
				$list['last_time'] = $list['update_time'] ? date('Y-m-d H:i', $list['update_time']) : date('Y-m-d H:i', $list['add_time']);
				unset($list['update_time']);
				unset($list['add_time']);
				$tmpName = array();
				$tmp = $list['menu_path'];
				while (strlen($tmp) > 0) {
					$i = M('semiautotag_menu')->where("menu_path = '{$tmp}'")->getField('menu_name');
					$tmpName[] = strlen($tmp) != 2 ? "<a href=\"/algorithm/platform?pid={$tmp}\">{$i}</a>" : "<a href=\"javascript:;\">{$i}</a>";
					$tmp = substr($tmp, 0, strlen($tmp)-2);

				}
				$list['menu_full_name'] = implode(' - ', array_reverse($tmpName));
			}
			$siluList['platform']['total_items'] = count($dlist);
			$siluList['platform']['items'] = $dlist;
			unset($dlist);
		}
		$this->assign('list', $siluList);
		$this->assign('user_id', $user_id);

		$this->loadJS('Algorithm/list', 'Algorithm/executor');
		$this->display();
	}

	public function add_semiauto()
	{
		$user_id = $this->me['user_id'];
		$device = $this->_get('device');
		if(!$device){
			$device = 'pc';
		}
		$this->assign('device', $device);
		$this->assign('campaign_ids', $this->_get('campaign_ids'));
		$this->assign('adgroup_ids', $this->_get('adgroup_ids'));

		$this->loadJS('Algorithm/editor');
		$this->display();
	}

	public function edit_semiauto()
	{
		$user_id = $this->me['user_id'];
		$this->assign('semiauto_id', $this->_get('semiauto_id'));

		$this->loadJS('Algorithm/editor');
		$this->display();
	}

	public function delete()
	{
		$return = array(
			'code'=>'error'
		);
		if($this->isPost()) {
			$id = I('id');
			try {
				$a = M('semiautotag')->where("id = {$id}")->find();
				if(!$a)
					throw new Exception("思路不存在", 1);
				if(($a['platform'] == 0 || $a['platform'] == 2) && $a['user_id'] != $this->me['user_id'])
					throw new Exception("思路不存在", 1);
				$res = M('semiautotag')->where('id = '.$id)->delete();
				$palt = M('semiautotag_platform')->where(array(
						'sem_iids' => array('LIKE', "%{$id}%"),
						'user_id' => $this->me['user_id']
					))->find();
				if($palt) {
					$o = explode(',', $palt['sem_iids']);
					$data['sem_iids'] = implode(',', array_diff($o, array($id)));
					$data['id'] = $palt['id'];
					$data['update_time'] = time();
					M('semiautotag_platform')->save($data);
				}
				if(!$res)
					throw new Exception("删除失败", 1);
				$return['code'] = 'success';
			} catch (Exception $e) {
				$return['msg'] = $e->getMessage();
			}
		}
		$this->display_json($return);
	}

	public function save()
	{
		$option = $this->_post();
		$data = array();
		$insertData = array();
		if(isset($option['indexs'])) {
			foreach ($option['indexs'] as $key => $areaor) {
				foreach ($areaor['info'] as $index) {
					$data['indexs'][$key][] = array(
						'intdex_name' => $index['intdex_name'],
						'intdex_condition' => autoCondition($index['intdex_condition']),
						'intdex_depth' => (int)$index['intdex_depth'],
						'intdex_srouceType' => (int)$index['intdex_srouceType'],
						'intdex_srouceValue' => $index['intdex_srouceValue'],
						'intdex_value' => $index['intdex_value']/100,
						'intdex_method' => (isset($index['intdex_method']) && in_array(strtolower($index['intdex_method']), array('and', 'or'))) ? $index['intdex_method'] : 'and'
					);
				}
			}
		}
		$data['date'] = (int)$option['date'];
		if(isset($option['priceModel']) && (int)$option['priceModel']['status'] == 1) {
			$data['priceModel']['status'] = 1;
			$data['priceModel']['priceType'] = (int) $option['priceModel']['priceType'];
			$data['priceModel']['priceValue'] = $option['priceModel']['priceValue'];
			if($data['priceModel']['priceType'] == 1) {
				$data['priceModel']['priceValue'] /= 100;
			}
			if(isset($option['priceModel']['optionType']))
				$data['priceModel']['optionType'] = (int)$option['priceModel']['optionType'];
			if(isset($option['priceModel']['priceExtreme']))
				$data['priceModel']['priceExtreme'] = $option['priceModel']['priceExtreme'];
		} else {
			$data['priceModel']['status'] = (int) $option['priceModel']['status'];
		}

		//删除
		$data['delete']['status'] = 0;
		if (isset($option['deleteModel']) && (int)$option['deleteModel'] == 1) {
			$data['delete']['status'] = 1;
		}

		$data['matchscopeModel']['status'] = (int) $option['matchscopeModel']['status'];
		if($data['matchscopeModel']['status'] > 0) {
			$data['matchscopeModel']['value'] = (int) $option['matchscopeModel']['value'];
		}

		$dataSource = ((int)$option['dataSource'] == 1 || (int)$option['dataSource'] == 0) ? (int)$option['dataSource'] : 1;
		$insertData['data_source'] = $dataSource;
		$insertData['title'] = $option['name'];
		$insertData['content'] = serialize($data);
		$insertData['add_time'] = time();
		$insertData['type'] = $data['indexs'][0][0]['intdex_depth'];
		if($data['indexs'][0][0]['intdex_depth'] == 3) {
			$insertData['type_value'] = $option['adgroup_id'];
		} else if ($data['indexs'][0][0]['intdex_depth'] == 2) {
			$insertData['type_value'] = $option['campaign_id'];
		} else {
			$me = session('me');
			$insertData['type_value'] = $me['user_id'];
		}
		if(isset($option['editOption']) && isset($option['editId']) && (int)$option['editId'] > 0 && $option['editOption'] == 'true') {
			if($data['indexs'][0][0]['intdex_depth'] == 3)
				$sql = "
					UPDATE 
						`semiautotag` 
					SET 
						title = '{$insertData['title']}',
						content = '{$insertData['content']}',
						data_source = {$insertData['data_source']}
					WHERE id = {$option['editId']}";
			else 
				$sql = "
					UPDATE 
						`semiautotag` 
					SET 
						title = '{$insertData['title']}',
						content = '{$insertData['content']}',
						type = {$insertData['type']},
						type_value = {$insertData['type_value']},
						data_source = {$insertData['data_source']}
					WHERE id = {$option['editId']}";
			$siluCaozuoType = 2;
		} else {
			$campaign_id = $option['campaign_id'];
			$adgroup_id = $option['adgroup_id'];
			$sql = "
				INSERT INTO
					semiautotag(
						user_id,
						title,
						content,
						add_time,
						type,
						type_value,
						campaign_id,
						adgroup_id,
						platform,
						data_source
					) 
				VALUES (
					{$this->me['user_id']},
					'{$insertData['title']}',
					'{$insertData['content']}',
					'{$insertData['add_time']}',
					{$insertData['type']},
					'{$insertData['type_value']}',
					'{$campaign_id}',
					'{$adgroup_id}',
					'0',
					{$insertData['data_source']}
				)";
			$siluCaozuoType = 1;
		}
		M()->execute($sql);
		// M('semiautotag')->create($insertData);
		$da = array(
				'msg' => '操作成功',
			);

		// 记录操作日志
		import('@.Library.SimbaLog');
		SimbaLog::save('semiautotag', array('method' => $siluCaozuoType, 'user_id' => $this->me['user_id']));
		
		$this->display_json($da);
	}

	public function execute()
	{
		$user_id = $this->me['user_id'];
		$unResult = $this->_post('un_silu_result');
		$keywords = $this->_post('keyword');
		$dataSource = $this->_post('source');
		$siluAcType = (int)$this->_post('siluAcType');
		$return = array(
				'status' => 0,
				'msg' => '未知错误'
			);
		$unActionCount = 0;
		if(!$unResult)
			$unResult = array();
		try {
			$keywords = json_decode($keywords, true);
			if(!$keywords)
				throw new Exception("暂无可执行的关键词", 1);
			$actionWord = array();
			if ($siluAcType === 1) {
				$shanchu = $this->_post('shanchu') === 'true' ? true : false;
				foreach ($keywords as $word) {
					if(!in_array($word['keyword_id'], $unResult)) {
						if($shanchu) {
							$actionWord[$word['campaign_id']][] = $word['keyword_id'];
						} else {
							if($word['del'] == 'true')
								$actionWord[$word['campaign_id']][] = $word['keyword_id'];
						}
					}
				}
			} else {
				$dataSource = $dataSource == 1 ? true : false; // true PC  flase W
				$zaicizhixing = $this->_post('zaicizhixing') === 'true' ? true : false;
				if(!$zaicizhixing) {
					foreach ($keywords as $id => $word) {
						if($word['executed']) {
							unset($keywords[$id]);
						}
					}
				}
				if($dataSource) {
					foreach ($keywords as $word) {
						if(!in_array($word['keyword_id'], $unResult)) {
							if($word['new_price'] != $word['max_price']) {
								$actionWord[] = array(
									'keywordId' => $word['keyword_id'],
									'maxPrice' => $word['new_price'] *100,
									'isDefaultPrice' => $word['is_default_price'] === true ? 1 : 0,
									'matchScope' => $word['new_matchscope']
								);
							} else {
								$unActionCount++;
							}
						}
					}
				} else {
					foreach ($keywords as $word) {
						if(!in_array($word['keyword_id'], $unResult)) {
							if($word['new_price'] != $word['max_price']) { 
								$actionWord[] = array(
									'keywordId' => $word['keyword_id'],
									'maxMobilePrice' => $word['new_price'] *100,
									'mobileIsDefaultPrice' => 0,
									'matchScope' => $word['new_matchscope']
								);
							} else {
								$unActionCount++;
							}
						}
					}
				}
			}
			
			// 执行思路
			$keywordMdl = new KeywordModel();
			if ($siluAcType === 1) {
				$res = $keywordMdl->deleteSemiautosKeywords($this->me['nick'], $this->me['user_id'], $actionWord);
			} else {
				$res = $keywordMdl->updateSemiautosKeywords($this->me['nick'], $this->me['user_id'], $actionWord);
			}
				
			if($res['code'] != 'success') {
				throw new Exception((($unActionCount > 0 && $siluAcType !== 1) ? "有{$unActionCount}个关键词新价格与当前价格相同，不执行改价。" : '')."{$res['msg']}", 1);
			}
			$return['status'] = 1;
			$return['msg'] = "执行成功！".(($unActionCount > 0 && $siluAcType !== 1) ? "有{$unActionCount}个关键词新价格与当前价格相同，不执行改价。" : '')."{$res['msg']}";

			// 记录操作日志
			import('@.Library.SimbaLog');
			SimbaLog::save('semiautotag', array('method' => 3, 'user_id' => $this->me['user_id']));
		} catch (Exception $e) {
			$return['msg'] = $e->getMessage();
		}
		
		$this->display_json($return);
	}

	public function getExecuteResult()
	{
		$me = session('me');
		$user_id = $me['user_id'];
		unset($me);
		$sId = (int)$this->_post('id');
		$thinkingInfo = M('semiautotag')->field('content, type, type_value, status, campaign_id,adgroup_id, data_source')->where("id = {$sId}")->find();
		$return = array(
				'status' => 0,
				'msg' => "未知错误"
			);
		try {
			if(!$thinkingInfo) {
				throw new Exception("思路不存在！", 1);
			}

			$adgroupMdl = new AdgroupModel;
			$keywordMdl = new KeywordModel;

			$content = unserialize($thinkingInfo['content']);
			$from = date('Y-m-d', strtotime("-{$content['date']} day"));
			$to = date('Y-m-d', strtotime('-1 day'));


			// 获取需要选词的adgroup_id 根据设置的数据维度进行自动判断
			if($thinkingInfo['type'] == 1) {

			} elseif ($thinkingInfo['type'] == 2) {
				
			} elseif ($thinkingInfo['type'] == 3) {
				// 固定的选择宝贝（当前宝贝）在多维度优化中使用
				// $adgroup_iids = $thinkingInfo['type_value'];
				$campaign_id = $thinkingInfo['campaign_id'];
				$adgroup_id = $thinkingInfo['adgroup_id'];
			} elseif ($thinkingInfo['type'] == 4) {
				// 自选的计划 或 推广组（宝贝）在批量优化中使用 4
				// 必须传递所选的计划 或者 推广组
				$campaign_id = $this->_post('campaign_id');
				$adgroup_id = $this->_post('adgroup_id');
			} else {
				throw new Exception("参数错误，请联系坤谷", 1);
			}

			$adgroup_iids = array();
			if(!$adgroup_id && !$campaign_id) {
				throw new Exception("请选择计划或推广组", 1);
			}

			if($adgroup_id) {
				$adgroup_iids = explode(',', urldecode($adgroup_id));
			}

			if($campaign_id) {
				$campaign_id = explode(',', urldecode($campaign_id));
				foreach ($campaign_id as $key => $id) {
	                $tmp = $adgroupMdl->getCampaignsAdgroups($user_id, $id, false, $from, $to, false, 0, 0, array(), array('online_status' => 'online'));
	                if($tmp)
	                    $adgroup_iids = array_merge($adgroup_iids, array_column($tmp, 'adgroup_id'));
	            }
			}
			if(!$adgroup_iids)
				throw new Exception("没有找到可用的推广组", 1);
				
			unset($tmp);

			$sql = "SELECT c.campaign_id, a.adgroup_id, c.title AS c_title, a.title AS a_title, a.img_url, a.category_ids FROM adgroups AS a JOIN campaigns AS c ON c.campaign_id = a.campaign_id WHERE a.adgroup_id IN (".implode(',', $adgroup_iids).")";
			$qy = M()->query($sql);
			$object_cus = array();
			$category_ids = array();
			if($qy) {
				foreach ($qy as $key => $value) {
					$tmp = explode(' ', $value['category_ids']);
					$tmp = array_reverse($tmp);
					$category_ids[] = $tmp[0];
					
					if(isset($object_cus[$value['campaign_id']])) {
						$object_cus[$value['campaign_id']]['detail'][] = $value;
					} else {
						$object_cus[$value['campaign_id']] = array(
								'base' => array(
										'title' => $value['c_title']
									),
								'detail' => array()
							);

						$object_cus[$value['campaign_id']]['detail'][] = $value;
					}
				}
			}
			if(count($category_ids) == 1) {
				$category_id = $category_ids[0];
			} else {
				$y = array_count_values($category_ids);
				arsort($y);
				$category_id = key($y);
				unset($y);
			}
			$object_cus = array(
					'total_items' => count($object_cus),
					'items' => $object_cus
				);

				
			// 整理选词条件
			$filters = array();
			foreach ($content['indexs'] as $index_key => $filter) {
				foreach ($filter as $index) {
					if($index['intdex_srouceType'] == 3) {
						$value = $index['intdex_srouceValue'] * $index['intdex_value'];
					} elseif ($index['intdex_srouceType'] == 4) {
						// $value = self::_getIndexReport($from, $to, $user_id, $vType, $campaign_id, $adgroup_id, $index['intdex_name']);
						$noAllowIndex = array('qscore', 'avgpos', 'cart_total', 'cart_total_rate');
						if(!in_array($index['intdex_name'], $noAllowIndex)) {
							$parmes['category_id'] = $category_id;
							$parmes['index'] = $index['intdex_name'];
							$parmes['start_date'] = $from;
							$parmes['end_date'] = $to;
							$value = R('Tools/getCatsData', array($parmes), 'Event');
						} else {
							$value = 0;
						}
						$value *= $index['intdex_value'];
					} else {
						$vType = (int)$index['intdex_srouceType'];// == 1 ? 'AVG' : 'MAX';
						$value = ($vType == 1) ? '宝贝均值' : '宝贝最大值';
					}
					if(!isset($filters[$index_key][$index['intdex_name']]))
						$filters[$index_key][$index['intdex_name']] = array(
								'method' => isset($index['intdex_method']) ? $index['intdex_method'] : 'and'
							);
					switch ($index['intdex_condition']) {
						case '>':
							$filters[$index_key][$index['intdex_name']]['min'] = array(
									'value' => $value,
									'eq' => false
								);
							break;
						case '=':
							$filters[$index_key][$index['intdex_name']]['min'] = array(
									'value' => $value,
									'eq' => true
								); //$value;
							$filters[$index_key][$index['intdex_name']]['max'] = array(
									'value' => $value,
									'eq' => true
								); // $value;
							// $filters[$index_key][$index['intdex_name']]['eq'] = true;
							break;
						case '<':
							$filters[$index_key][$index['intdex_name']]['max'] = array(
									'value' => $value,
									'eq' => false
								);
							break;
						case '>=':
							$filters[$index_key][$index['intdex_name']]['min'] = array(
									'value' => $value,
									'eq' => true
								);
							// $filters[$index_key][$index['intdex_name']]['eq'] = true;
							break;
						case '<=':
							$filters[$index_key][$index['intdex_name']]['min'] = array(
									'value' => isset($filters[$index_key][$index['intdex_name']]['min']['value']) ? $filters[$index_key][$index['intdex_name']]['min']['value'] : 0,
									'eq' => isset($filters[$index_key][$index['intdex_name']]['min']['eq']) ? $filters[$index_key][$index['intdex_name']]['min']['eq'] : true,
								);
							$filters[$index_key][$index['intdex_name']]['max'] = array(
									'value' => $value,
									'eq' => true
								);
							// $filters[$index_key][$index['intdex_name']]['eq'] = true;
							break;
					}
				}
			}
			
			// 设置调价信息
			if($content['priceModel']['status'] == 1) {
				if($content['priceModel']['priceType'] == 1) {
					$is_auto_price = 'new_true';
					$auto_price_type = 'addpricewithratio'; // 百分比调价
					
					$new_pre = $content['priceModel']['optionType'] == 1 ? (1-$content['priceModel']['priceValue']) : (1+$content['priceModel']['priceValue']);
					// $new_pre = $content['priceModel']['priceValue'];
					$custom_max_price = $content['priceModel']['priceExtreme']*100; // 最大价格 转化为分 （元 -> 分）

					$is_max = $content['priceModel']['optionType'] == 1 ? false : true;

				} else if($content['priceModel']['priceType'] == 2) {
					$is_auto_price = 'new_true';
					$auto_price_type = 'addbyfix'; // 原基础调价
					
					$new_pre = $content['priceModel']['optionType'] == 1 ? -$content['priceModel']['priceValue'] : $content['priceModel']['priceValue'];
					$custom_max_price = $content['priceModel']['priceExtreme']*100; // 最大价格 转化为分 （元 -> 分）

					$is_max = $content['priceModel']['optionType'] == 1 ? false : true;
				} else {
					$is_auto_price = 'new_false';
					// 手动调价
					$new_pre = $content['priceModel']['priceValue']*100;
				}
			} else {
				$is_auto_price = 'self';
			}

			// 设置关键词匹配信息
			if($content['matchscopeModel']['status'] == 1) {
				$new_matchscope = $content['matchscopeModel']['value'] == 1 ? 4 : ($content['matchscopeModel']['value'] == 2 ? 2 : 1);
			}

			// 获取所有条件内的关键词
			$res = $keywordMdl->getSemiautosKeywords($sId, 'display', '', $adgroup_iids);
			if($res['code'] != 'success') {
				throw new Exception("{$res['msg']}:{$res['detail']}", 1);
			}
			$keywords = array();
			$siluType = (int)$res['result']['device'];
			$res = $res['result']['response'];
			if($res) {
				$modifiedKeyword = S("action_keywords_{$user_id}");
				foreach ($res as $obj) {
					foreach($obj['words'] as $key_id => &$keyword) {
						$keyword['a_title'] = $obj['adgroup']['title'];
						$keyword['adgroup_id'] = $obj['adgroup']['adgroup_id'];
						$keyword['campaign_id'] = $obj['adgroup']['campaign_id'];
						$keyword['img_url'] = $obj['adgroup']['img_url'];
						$keyword['cost'] = $keyword['cost']*0.01;
						$keyword['sales'] = $keyword['sales']*0.01;
						$keyword['max_price'] = $siluType == 2 ? price_display_str(floatval($keyword['max_price']*0.01)) : price_display_str(floatval($keyword['max_mobile_price']*0.01));
						$keyword['new_price'] = $siluType == 2 ? price_display_str(floatval($keyword['new_price']*0.01)) : price_display_str(floatval($keyword['new_mobile_price']*0.01));
						$keyword['cart_total'] = $keyword['cart_count'];
						$keyword['cart_total_rate'] = $keyword['cart_count_rate'];
						unset($keyword['cart_count']);
						unset($keyword['cart_count_rate']);
						if($keyword['new_matchscope'] === 0)
							unset($keyword['new_matchscope']);

						$keyword['modifiedStatus'] = 0;
						if($modifiedKeyword && in_array($keyword['keyword_id'], $modifiedKeyword['all_keyword_iids'])) {
							$keyword['modifiedStatus'] = 1;
						}
					}
					$keywords = array_merge($keywords, $obj['words']);
				}
				unset($modifiedKeyword);
			}
			
			$return = array(
						'status' => 1,
						'total_items' => count($keywords),
						'items' => $keywords,
						'adgroup_iids' => $adgroup_iids,
						'campaign_id' => $campaign_id,
						'adgroup_id' => $adgroup_id,
						'filters_string' => siluFilters($filters, $thinkingInfo['content']),
						'object' => createObject($object_cus)
					);
			unset($res);
		} catch (Exception $e) {
			$return['msg'] = $e->getMessage();
		}
		$this->display_json($return);	
	}

	private function _getIndexReport($from, $to, $user_id, $source, $campaign_id, $adgroup_id, $index)
	{
		$sKey = md5("{$from}_{$to}_{$user_id}_{$source}_{$campaign_id}_{$adgroup_id}_silu");
		$data = S($sKey);
		if(!$data) {
			$parmes = array(
					'user_id' => $user_id,
					'campaign_id' => $campaign_id,
					'adgroup_id' => $adgroup_id,
					'index' => $index,
					'source' => $source,
					'from' => $from,
					'to' => $to
				);
			$data = R('Adgroups/getIndexData', array($parmes), 'Event');
		}
		return $data[$index] ? $data[$index] : 0;
	}

	public function status()
	{
		$id = $this->_get('id');
		$thinkingInfo = M('semiautotag')->field('status')->where("id = {$id} AND user_id = {$this->me['user_id']}")->find();
		if($thinkingInfo && $thinkingInfo['status'] == 2) {
			$arr = array(
					'status' => 1
				);
			M('semiautotag')->where("id = {$id}")->save($arr);
		}

		redirect('/algorithm/condition');
	}

	public function getIndexReport()
	{
		$user_id = $this->me['user_id'];
		$campaign_id = $this->_post('campaign_id');
		$adgroup_id = $this->_post('adgroup_id');
		$date = (int)$this->_post('date');
		$index = $this->_post('index');
		$source = $this->_post('source');
		$dataSource = (int)$this->_post('data_source');

		if($index == 'qscore' && $dataSource == 0)
			$index = 'wireless_qscore';

		$from = date('Y-m-d', strtotime("-{$date} day"));
		$to = date('Y-m-d', strtotime("-1 day"));
		unset($date);
		$sKey = md5("{$from}_{$to}_{$user_id}_{$source}_{$campaign_id}_{$adgroup_id}_silu_{$dataSource}");
		$data = S($sKey);
		if(!$data) {
			try {
				switch ((int)$source) {
					case 4:
						$parmes = array();
						$where = "user_id = {$user_id}";
						if($campaign_id && $adgroup_id) {
							$where .= " AND (campaign_id IN (" . implode(',', $campaign_id) . ") OR adgroup_id IN (" . implode(',', $adgroup_id) . "))";
						} else if($campaign_id) {
							$where .= " AND campaign_id IN (" . implode(',', $campaign_id) . ")";
						} else if($adgroup_id) {
							$where .= " AND adgroup_id IN (" . implode(',', $adgroup_id) . ")";
						} else {
							throw new Exception("请选择数据对象!", 1);
						}
						$res = M('adgroups')->where($where)->getField('adgroup_id, category_ids');
						$category_ids = array();
						$category_id = '';
						foreach ($res as $key => $value) {
							$tmp = explode(' ', $value);
							$tmp = array_reverse($tmp);
							$category_ids[] = $tmp[0];
						}

						if(count($category_ids) == 1) {
							$category_id = $category_ids[0];
						} else {
							$y = array_count_values($category_ids);
							arsort($y);
							$category_id = key($y);
							unset($y);
						}

						// $value = self::_getIndexReport($from, $to, $user_id, $vType, $campaign_id, $adgroup_id, $index['intdex_name']);
						$noAllowIndex = array('qscore', 'avgpos', 'cart_total', 'cart_total_rate');
						if(!in_array($index, $noAllowIndex)) {
							$parmes['category_id'] = $category_id;
							$parmes['index'] = $index;
							$parmes['start_date'] = $from;
							$parmes['end_date'] = $to;
							$parmes['data_source'] = $dataSource;
							$data[$index] = R('Tools/getCatsData', array($parmes), 'Event');
						} else {
							$data[$index] = 0;
						}
					break;
					default:
						$parmes = array(
								'user_id' => $user_id,
								'campaign_id' => $campaign_id,
								'adgroup_id' => $adgroup_id,
								'index' => $index,
								'source' => $source,
								'from' => $from,
								'to' => $to,
								'data_source' => $dataSource
							);
						$data = R('Adgroups/getIndexData', array($parmes), 'Event');
						break;
				}
			} catch (Exception $e) {
				$this->error($e->getMessage());
				die;
			}
		}
		$this->display_json(isset($data[$index]) ? $data[$index] : 0);
	}

	public function getSilu()
	{
		$id = (int)$this->_post('id');

		$type = $this->_post('type');
		$return = array(
				'status' => 0,
				'msg' => '未知错误'
			);
		$field = $type == 'detail' ? 'id,content, type, type_value, status,title,adgroup_id, campaign_id,data_source' : 'title,type,content, type_value,campaign_id,adgroup_id,data_source';
		$info = M('semiautotag')->field($field)->where("id = {$id}")->find();
		try {
			if(!$info) {
				throw new Exception("思路不存在！", 1);
			}

			

			$return['status'] = 1;
			unset($return['msg']);
			if($type == 'detail') {
				$info['content'] = unserialize($info['content']);
				$info['content']['priceModel']['priceValue'] = $info['content']['priceModel']['priceType'] == 1 ? $info['content']['priceModel']['priceValue'] * 100 : $info['content']['priceModel']['priceValue'];
				foreach ($info['content']['indexs'] as $key => $value) {
					foreach ($value as $index_key => $index_value) {
						$info['content']['indexs'][$key][$index_key]['intdex_value'] *= 100;
					}
				}
				
			} else {
				$tmp = unserialize($info['content']);
				$info['actionType'] = $tmp['delete']['status'] == 1 ? 1 : 0;
				unset($info['content']);
				unset($tmp);
			}
			$info['data_source'] = (int)$info['data_source'];
			$return['data'] = $info;
		} catch (Exception $e) {
			$return['msg'] = $e->getMessage();
		}
		$this->display_json($return);
	}

	public function platform()
	{
		$pid = $this->_get('pid');
		$menuTree = array();
		$viewType = 'view';
		if(strlen($pid)%2 == 0) {
			// $menu_id = $this->_get('mid');
			$modules = M('semiautotag_menu')->where("status != 0 and menu_path LIKE '{$pid}%' ")->order('menu_order asc')->select();
			$menuTree = menuTree($modules, $pid);
		}

		if(count($menuTree) == 1 && !isset($menuTree[0]['items'])) {
			$siluRes = M('semiautotag')->where("platform = {$pid}")->select();
			if($siluRes) {
				foreach ($siluRes as $key => &$list) {
					$list['content'] = analyticalThinking($list['content']);
					$list['add_time'] = date('Y-m-d H:i', $list['add_time']);
				}
			}
			$ylist = array('total_items' => count($siluRes), 'items'=> $siluRes);
			$this->assign('list', $ylist);
			$viewType = 'list';
		}
		$this->assign('viewType', $viewType);
		$this->assign('menu', $menuTree);
		$this->assign('user_id', $this->me['user_id']);
		$this->loadJS('custom.siluhelper');
		$this->display();
	}

	public function getPlatformMenu()
	{
		$pid = $this->_post('pid');
		$sync = $this->_post('sync');
		$last = $this->_post('last');
		$return = array(
					'status' => 1
				);
		if($last === 'true') {
			$y = strlen($pid)+2;
			$res = M('semiautotag_menu')->field('MAX(menu_path) AS max_path')->where("menu_path LIKE '{$pid}%' AND LENGTH(menu_path) = {$y}")->find();
			$mx = (int) $res['max_path'];
			if($mx)
				$return['platform'] = ++$mx;
			else
				$return['platform'] = $pid . '10';
			$return['div'] = '';
		} else {
			if(strlen($pid)%2 == 0) {
				
				$where = ($sync == "true" ? '' : 'status != 0 AND ') . "menu_path LIKE '{$pid}%'";
				if($pid) {
					$num = strlen($pid) + 2;
					$where .= " AND (length(menu_path) = {$num} OR length(menu_path) = " . strlen($pid) . ")";
				}
				$modules = M('semiautotag_menu')->where($where)->order('menu_order asc')->select();
				$menuTree = menuTree($modules, $pid);
			}
			
			if($menuTree) {

				$return['div'] = "<div class=\"v1\"><select name=\"\" class=\"change-platform\" data-parent-path=\"{$pid}\"><option value=\"\">请选择</option>";
				if(!$pid) {
					foreach ($menuTree as $key => $menu) {
						$return['div'] .= "<option value=\"{$menu['info']['path']}\">{$menu['info']['title']}</option>";
					}
					$return['div'] .= "</select></div>";
				} else {
					if(isset($menuTree[0]['items'])) {
						foreach ($menuTree[0]['items'] as $key => $menu) {
							$return['div'] .= "<option value=\"{$menu['path']}\">{$menu['title']}</option>";
						}
						$return['div'] .= "</select></div>";
					} else {
						$return['div'] = '';
						$return['platform'] = $pid;
						
					}
				}
			}
		}
			
		$this->display_json($return);
	}

	public function toPlatformSilu()
	{
		$return = array(
				'status' => 0
			);
		$platform = $this->_post('platform');
		$siluId = htmlspecialchars($this->_post('siluId'));
		if($siluId && $platform) {
			$sql = "UPDATE semiautotag SET platform = '$platform' , user_id = '' WHERE id = '{$siluId}'";
			$y = M()->execute($sql);
			if($y)
				$return['status'] = 1;
			else {
				$return['msg'] = '转移失败，请重试';
			}
		} else {
			$return['msg'] = '信息出错，请重试';
		}
		$this->display_json($return);
	}

	public function cpoySilu()
	{
		$return = array(
				'status' => 0
			);
		
		$avaliable_methods = array('multi','single');
		$method = $this->_post('method');
        if(!in_array($method, $avaliable_methods)) {
           $return['msg'] = "非法请求！";
        } else {
        	$siluMdl = M('semiautotag');
        	switch ($method) {
        		case 'multi':
        			$path_id = $this->_post('path_id');
        			$searchWhere = "platform = {$path_id}";
        			break;
        		case 'single':
        			$silu_id = $this->_post('silu_id');
        			$searchWhere = "id = {$silu_id}";
        			break;
        	}
        	$siluRes = $siluMdl->where($searchWhere)->select();
        	
        	if($siluRes) {
        		$menu_path = $siluRes[0]['platform'];
        		$datas = array();
        		$time = time();
        		foreach ($siluRes as $key => $silu) {
        			$data = array(
        					'user_id' => $this->me['user_id'],
							'title' => $silu['title'],
							'content' => $silu['content'],
							'add_time' => $time,
							'type' => $silu['type'],
							'type_value' => $silu['type_value'],
							'campaign_id' => $silu['campaign_id'],
							'adgroup_id' => $silu['adgroup_id'],
							'platform' => '2'
        				);
        			$datas[] = $siluMdl->add($data);
        		}
        		$current_local_plat = M('semiautotag_platform')->where("user_id = {$this->me['user_id']} AND menu_path = {$menu_path}")->find();
        		if($current_local_plat) {
        			$tmp['id'] = $current_local_plat['id'];
        			$tmp['update_time'] = time();
        			$tmp['sem_iids'] = $current_local_plat['sem_iids'];
        			$tmp['sem_iids'] .= $tmp['sem_iids'] ? (',' . implode(',', $datas)) : implode(',', $datas);
        			M('semiautotag_platform')->save($tmp);
        		} else {
        			M('semiautotag_platform')->add(
        					array(
        							'user_id' => $this->me['user_id'],
        							'menu_path' => $menu_path,
        							'sem_iids' => implode(',', $datas),
        							'add_time' => time()
        						)
        				);
        		}
        		$return['status'] = 1;
        	} else {
        		$return['msg'] = "没有搜索到相应的思路，请重试。";
        	}
        }
		$this->display_json($return);
	}

	public function getMyCopyById()
	{
		$id = $this->_post('id');
		try {
			$return = array(
					'status' => 0,
					'total_items' => 0
				);
			if((int) $id == 0)
				throw new Exception("接口不存在", 1);

			$sem_iids = M('semiautotag_platform')->where("id = {$id} AND user_id = {$this->me['user_id']}")->getField('sem_iids');
			$res = M('semiautotag')->field('id, title, content, add_time')->where("id IN ({$sem_iids})")->select();
			if($res) {
				foreach ($res as $key => &$silu) {
					$silu['content'] = analyticalThinking($silu['content']);
					$silu['add_time'] = date('Y-m-d H:i:s', $silu['add_time']);
				}
				$return['total_items'] = count($res);
				$return['items'] = $res;
			}
			unset($res);
		} catch (Exception $e) {
			$return['status'] = 1;
			$return['msg'] = $e->getMessage();
		}
		
		$this->display_json($return);
	}

	// 思路后台
	public function siluPlatform()
	{
		if(!session('?admin')) {
			$this->error("权限不足");
		}
		$this->loadJS('treeview/jquery.treeview', 'simditor/simple-module', 'simditor/simple-hotkeys', 'simditor/simple-uploader', 'simditor/simditor', 'upload/jquery.fileupload');
		$menuTopTmp = M('semiautotag_menu')->where('LENGTH(menu_path) = 2')->order('menu_order ASC')->select();
		$menuOrder = M('semiautotag_menu')->where('LENGTH(menu_path) != 2')->order('menu_order ASC')->select();
		$menuTop = array();
		foreach ($menuTopTmp as $key => $mt) {
			$menuTop[$mt['menu_path']]['info'] = array(
					'id' => $mt['menu_id'],
					'name' => $mt['menu_name'],
					'path' => $mt['menu_path']
				);
		}
		unset($menuTopTmp);
		import('@.Library.Tools');
		$html = "<ul id=\"browser\" class=\"filetree\">";
		foreach ($menuTop as $key => &$value) {
			$html .= "<li class=\"silu-menu\" data-path=\"{$value['info']['path']}\" data-id=\"{$value['info']['id']}\">";
			$html .= "<div class=\"box-tools menu-tools-{$value['info']['path']}\">";
			foreach (C('SILU_MENU_TOOLS') as $tool) {
				$html .= "<a class=\"{$tool['icon']}\" href=\"javascript:;\" title=\"{$tool['name']}\"></a>";
			}
			$html .= "</div><span class=\"folder\">{$value['info']['name']}</span>";
			$value['list'] = Tools::createMenuTree($menuOrder, $value['info']['path']);
			if($value['list'])
				$html .= Tools::createMenuHtml($value['list']);
			$html .= "</li>";
		}
		$html .= "</ul>";
		$this->assign('menuTree', $html);
		$this->display();
	}

	public function getMenuInfo()
	{
		if(!session('?admin')) {
			$this->error("权限不足");
		}
		$return = array(
				'error' => 1,
			);
		$menu_id = $this->_post('menu_id');
		$res = M('semiautotag_menu')->field('menu_id, menu_name, menu_path, menu_icon, summary, status')->find($menu_id);
		if($res) {
			import('@.Library.Tools');


			$current_path = $res['menu_path'];
			$current_path_len = strlen($res['menu_path'])/2;
			$current_path_len = $current_path_len == 1 ? 1 : --$current_path_len;
			$parentUnit = substr($current_path, 0, 2);
			$menuList = array();

			for ($i=0; $i < $current_path_len; $i++) { 
				if($i == 0) {
					$tmp = M('semiautotag_menu')->where('LENGTH(menu_path) = 2')->order('menu_order ASC')->select();
				} else {
					$path = substr($current_path, 0, $i * 2);
					$where = "menu_path LIKE '{$path}%' AND LENGTH(menu_path) = " .($i+1) * 2;
					$tmp = M('semiautotag_menu')->where($where)->order('LENGTH(menu_path) ASC')->select();
				}
				$menuList = array_merge($menuList, $tmp);
			}
			$top = array();
			foreach ($menuList as $key => $menu) {
				if(strlen($menu['menu_path']) == 2) {
					$top[$menu['menu_path']]['info'] =  array(
								'id' => $menu['menu_id'],
								'name' => $menu['menu_name'],
								'path' => $menu['menu_path']
							);
					unset($menuList[$key]);
				}
				if($menu['menu_path'] == $parentUnit) {
					$top[$menu['menu_path']]['list'] = Tools::createMenuTree($menuList, $menu['menu_path']);
				}
			}
			$select = array();
			Tools::createMenuSelect($top, 1, $select, $current_path);
			$return['error'] = 0;
			$return['item'] = $res;
			$return['item']['menu_path_select'] = implode(' ', $select);
			// $return['item']['menu_parent_path'] = 
		} else {
			$return['msg'] = '策略不存在，请重新选择';
		}
		$this->display_json($return);
	}

	public function addMenu()
	{
		$return = array(
				'status' => 0,
				'msg' => '未知错误'
			);
		$data = array();

		$rule = array(
				'menu_name' => array(
						'data' => 'noemtpy',
						'msg' => '请正确填写策略名称'
					),
				'menu_path' => array(
						'data' => 'noemtpy',
						'msg' => '请正确选择所属策略'
					)
			);
		$menu_id = $this->_post('menu_id');
		$data['menu_name'] = $this->_post('menu_name');
		$data['menu_path'] = $this->_post('menu_path');
		$data['menu_icon'] = $this->_post('menu_icon');
		$data['summary'] = $this->_post('summary');
		$data['status'] = $this->_post('status');
		try {
			foreach ($rule as $key => $item) {
				switch ($item['data']) {
					case 'noemtpy':
					default:
						if(!isset($data[$key]) || !$data[$key])
							throw new Exception($item['msg'], 1);
						break;
				}
			}
			$semMenuMdl = M('semiautotag_menu');
			if(!$menu_id) {
				// 新增的
				if($semMenuMdl->add($data)) {
					$return['status'] = 1;
					unset($return['msg']);
				} else
					$return['msg'] = "保存失败，请重试";
			} else {
				// 存在的（修改）
				$current_menu = $semMenuMdl->find($menu_id);
				
				if($current_menu) {
					$data['menu_id'] = $menu_id;
					$semMenuMdl->save($data);
					$return['status'] = 1;
					unset($return['msg']);
				} else {
					$return['msg'] = '未知错误，请重试';
				}
			}
		} catch (Exception $e) {
			$return['msg'] = $e->getMessage();
		}

		$this->display_json($return);
	}

	public function delMenu()
	{
		$menu_id = $this->_post('menu_id');
		$return = array(
				'status' => 0,
				'msg' => '未知错误'
			);
		try {
			if(!$menu_id)
				throw new Exception("策略不存在，请重新选择", 1);
			$semMenuMdl = M('semiautotag_menu');
			$current_menu = $semMenuMdl->find($menu_id);
			if($current_menu) {
				
				$res = $semMenuMdl->field('COUNT(menu_id) AS num')->where("menu_path LIKE '{$current_menu['menu_path']}%' AND LENGTH(menu_path) > ".strlen($current_menu['menu_path']))->find();
				if((int) $res['num'] > 0)
					throw new Exception("请先删除子策略后再进行此操作", 1);
				$semMdl = M('semiautotag');
				$res = $semMdl->field('COUNT(id) AS num')->where("platform = '{$current_menu['menu_path']}'")->find();
				if((int) $res['num'] > 0)
					throw new Exception("策略下存在思路，请先删除思路后再进行此操作", 1);
				else {
					$semMenuMdl->where(array('menu_id' => $menu_id))->delete();
					$return['status'] = 1;
					unset($return['msg']);
				}
			} else {
				throw new Exception("策略不存在，请重新选择", 1);
			}
		} catch (Exception $e) {
			$return['msg'] = $e->getMessage();
		}
		$this->display_json($return);
	}
	public function condition_choose(){
	    $this->loadJS('custom.siluhelper');
	    $this->display();
	}
}
